/* 
 * File:   ButtonXpackDetector.cpp
 * Author: minaev
 * 
 * Created on 23 Декабрь 2013 г., 12:54
 */

#include "ButtonXpackDetector.h"

ButtonXpackDetector::ButtonXpackDetector(XbeeContainer* xcont) : XpackDetector(xcont) {
}

uint8_t ButtonXpackDetector::getXpackType() {
    return XAPI_RX_IO_RECV;
}

//[ 0x92, 
//  0x0, 0x13, 0xa2, 0x0, 0x40, 0xa1, 0x9f, 0xb0, 
//  0x44, 0xae, 0x41, 0x1, 0x0, 0x6, 0x0, 0x0, 0x0, ]             --- off

//[ 0x92, 
//  0x0, 0x13, 0xa2, 0x0, 0x40, 0xa1, 0x9f, 0xb0, 
//  0x44, 0xae, 0x41, 0x1, 0x0, 0x6, 0x0, 0x0, 0x2, ]             --- on

//0x000006000141ae44 - scan message
//0x000106000141ae44 - only ADC

bool ButtonXpackDetector::isXpackValid(Xpack* pack) {
    if (pack->getLength() > 16) {
        return *(uint32_t*) (pack->getData() + 11)
                == 0x06000141 &&
                *(uint8_t*) (pack->getData() + 15) == 0x01; //only with ADC
    } else {
        return false;
    }
    /*return  *(uint64_t*) (pack->getData() + 9) == 0x000006000141ae44 ||
     *(uint64_t*) (pack->getData() + 9) == 0x000106000141ae44;*/
    //pack->getByte(17) == 2;
}

void ButtonXpackDetector::action(Xpack* pack) {
    uint8_t reqStat;
    uint8_t curStat;
    uint32_t buf;

    int nblock = xcont->findById(*(uint32_t*) (pack->getData() + 5));

    if (nblock != -1) {
        reqStat = *(uint8_t*) xcont->getParam(nblock, SLN_XREQSTAT);
        curStat = *(uint8_t*) xcont->getParam(nblock, SLN_XSTAT);

        buf = ((*(uint8_t*) (pack->getData() + 17) & 0x2) >> 1);
        if (buf == 1) {
            xcont->setParam(nblock, SLN_XBTNS, (void*) &(buf = 1));
        }

        if ((*(uint8_t*) xcont->getParam(nblock, SLN_XBTNS)) == 1) {
            Xmsg::printf("ALARM button!!!\n");
            xcont->sendBtnStatusMessage(nblock);
        }

        if (*(uint8_t*) xcont->getParam(nblock, SLN_XBTNS) !=
                *(uint8_t*) xcont->getParam(nblock, SLN_XBTNOLDS)) {
            if ((*(uint8_t*) xcont->getParam(nblock, SLN_XBTNS)) == 1) {
                xcont->pinAlarmOn(nblock);
            } else {
                xcont->pinAlarmOff(nblock);
            }
            xcont->setParam(nblock, SLN_XBTNOLDS,
                    xcont->getParam(nblock, SLN_XBTNS));
        }
    }
}

